#include "serialportmanager.h"
#include "qextserialport.h"
#include <QDebug>

SerialPortManager::SerialPortManager(QObject *parent) :
    QObject(parent)
  , Port()
{
    connect(&Port, SIGNAL(readyRead()), this, SLOT(BufferData()));
}

SerialPortManager::~SerialPortManager()
{
}

void SerialPortManager::OpenPort(QString PortString)
{
    Port.setPortName(PortString);
    Port.setBaudRate(BAUD115200);
    Port.setDataBits(DATA_8);
    Port.setParity(PAR_NONE);
    Port.setStopBits(STOP_1);
    Port.setFlowControl(FLOW_OFF);
    Port.open(QIODevice::ReadWrite);
}

void SerialPortManager::ClosePort()
{
    Port.close();
}

QString SerialPortManager::ReadLine()
{
    if(!BufferedLines.isEmpty())
    {
        return BufferedLines.takeFirst();
    }
    else
    {
        return QString();
    }
}

bool SerialPortManager::HasLinesToRead()
{
    return !BufferedLines.isEmpty();
}

void SerialPortManager::SendLine(QString line)
{
    qDebug() << "Sending " << line;
    if(Port.isOpen())
    {
        Port.write(line.toLatin1() + '\r');
    }
}

void SerialPortManager::BufferData()
{
    QString rawStringData = Port.readAll();
    QStringList splitStringData = (Buffer + rawStringData).split('\r');

    if(!rawStringData.endsWith("\r"))
    {
        Buffer = splitStringData.takeLast();
    }
    else
    {
        Buffer = "";
    }

    if(!splitStringData.isEmpty())
    {
        BufferedLines.append(splitStringData);
        emit LineReadyToRead();
    }
}

